package com.xfapp.demos.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xfapp.demos.common.JwtUtil;
import com.xfapp.demos.common.Result;
import com.xfapp.demos.entity.LoginData;
import com.xfapp.demos.entity.User;
import com.xfapp.demos.entity.UserNickUrl;
import com.xfapp.demos.service.IUserService;
import com.xfapp.demos.util.WechatDecryptUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.connector.Request;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class WxLoginController {
    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String appSecret;

    private final RestTemplate restTemplate = new RestTemplate();

    @Resource
    private IUserService service;

    @PostMapping("/judge")
    public Result LonginApp(@RequestBody LoginData data){
        try{
            String code = data.getCode();
            String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    appId, appSecret, code);
//            String openid = JSONObject.parseObject(url).getString("openid");
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            String responseBody = responseEntity.getBody();
            JSONObject jsonObject = JSONObject.parseObject(responseBody);
            String openid = jsonObject.getString("openid");
            User user = service.getOne(new QueryWrapper<User>().eq("openid", openid));
            //用户第一次登录，解析用户资料，并且保存到数据库
            if (user == null){
                // 获取当前日期和时间
                LocalDateTime currentDateTime = LocalDateTime.now();
                user = new User(null
                        ,"","","",0,openid,data.getNickName(),data.getAvatarUrl(),currentDateTime,0
                );
                service.save(user);
            }
            Map<String, Object> map = new HashMap<>();
            String token = JwtUtil.createToken(user);
            map.put("token",token);
            map.put("id",user.getId());
            map.put("avatarUrl",user.getAvatar());
            map.put("nickName",user.getNickname());
            //生成token返回给前端
            return Result.success(map);

        }catch(Exception e) {
            return Result.error("-1","登录错误: " + e.getMessage());
        }
    }

    @PostMapping("/decrypt")
    public Result<Object> decryptData(@RequestBody LoginData data) {
        System.out.println("Received request: " + data.getCode());
        System.out.println("Received request: " + data.getIv());
        System.out.println("Received request: " + data.getEncryptedData());
        Map<String, Object> response = new HashMap<>();
        Result<Object> result = Result.success();
        try {
            String code = data.getCode();
            String encryptedData = data.getIv();
            String iv = data.getEncryptedData();

            // 1. 获取 session_key
            String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    appId, appSecret, code);
            System.out.println("url: " + url);
            // 使用 getForEntity 获取字符串响应
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            String responseBody = responseEntity.getBody();
            System.out.println(responseBody);
            // 2. 手动解析 JSON 字符串为 Map
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> wxResponse = objectMapper.readValue(responseBody, new TypeReference<Map<String, Object>>() {});
            System.out.println("wxResponse: " + wxResponse);
            if (wxResponse == null || wxResponse.containsKey("errcode")) {
                System.out.println("我执行了退出");
                return result.UserDefine("-1","微信接口错误: " + wxResponse.get("errmsg"),null);
            }
            String sessionKey = (String) wxResponse.get("session_key");
            // 2. 解密数据
            String userData = WechatDecryptUtil.decrypt(encryptedData, iv, sessionKey);
            System.out.println("userData:" + userData);
            return result.UserDefine("0","成功",userData);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "解密失败: " + e.getMessage());
            return result.UserDefine("-1","解密失败: " + e.getMessage(),null);
        }
    }

    @GetMapping("/secure/getUserInfo")
    public Result getInfo(HttpServletRequest request){
        Long id = Long.parseLong(request.getAttribute("id").toString());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        User user = service.getOne(queryWrapper);
        Map userData = new HashMap();
        userData.put("nickName",user.getNickname());
        userData.put("avatarUrl",user.getAvatar());
        return Result.success(userData);
    }

    @PostMapping("/secure/saveInfo")
    public Result saveInfo(HttpServletRequest request, @RequestBody UserNickUrl user){
        Long id = Long.parseLong(request.getAttribute("id").toString());
        String nickName = request.getAttribute("nickName").toString();
        String avatarUrl = request.getAttribute("avatarUrl").toString();
//        User user = service.getById(id);
//        user.setAvatar(avatarUrl);
//        user.setNickname(nickName);
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("nickname",user.getNickName());
        updateWrapper.set("avatar",user.getAvatarUrl());
        boolean update = service.update(updateWrapper);
        if(update){
            return Result.success("更新成功");
        }else {
            return Result.error("-1","更新失败");
        }
    }

    //用于校验请求拦截和校验token
    @GetMapping("/secure/checkToken")
    public void checkToken(HttpServletRequest request)
    {

    }

}
